//
//  HACBrushCandle.m
//  HStockCharts
//
//  Created by Hotacool on 2018/9/20.
//

#import "HACBrushCandle.h"
#import "HACBasicComponents.h"
#import "HACPainter.h"
#import "HACRectProvider.h"

@interface HACBrushCandle ()
// 只创建3个画笔，不以单个candle为单位来区分画笔。节省空间、提高效率，避免candle独立刷新导致的闪动问题。
@property (nonatomic, strong) HACPathPainter *player_up;
@property (nonatomic, strong) HACPathPainter *player_down;
@property (nonatomic, strong) HACPathPainter *player_equal;
@end

@implementation HACBrushCandle

- (instancetype)initWithDataProvider:(id<HACChartDataProvider>)provider {
    if (self = [super initWithDataProvider:provider]) {
        _player_up = [HACPathPainter painterLayer];
        _player_down = [HACPathPainter painterLayer];
        _player_equal = [HACPathPainter painterLayer];
    }
    return self;
}

- (void)clean {
    [self.player_up clearContents];
    [self.player_down clearContents];
    [self.player_equal clearContents];
}

- (void)removeBrush {
    [self.player_up removeFromSuperlayer];
    [self.player_down removeFromSuperlayer];
    [self.player_equal removeFromSuperlayer];
}

- (void)drawInLayer:(CALayer *)layer inRect:(CGRect)rect {
    [super drawInLayer:layer inRect:rect];
    [[self.player_up clearContents] removeFromSuperlayer];
    [[self.player_down clearContents] removeFromSuperlayer];
    [[self.player_equal clearContents] removeFromSuperlayer];
    
    NSArray *datas;
    if ([self.provider conformsToProtocol:@protocol(HACRectProvider)]) {
        id<HACRectProvider> provider = self.provider;
        datas = [provider rectDatasInRect:rect];
    }
    int idx = 0;
    for (HACRectComponents *rectItem in datas) {
        HACPathPainter *player;
        if (rectItem.valueType == DrawingUpValue) {
            player = self.player_up;
        } else if (rectItem.valueType == DrawingDownValue) {
            player = self.player_down;
        } else {
            player = self.player_equal;
        }
        player.strokeColor = rectItem.lineColor.CGColor;
        player.lineWidth = rectItem.lineBolder;
        player.fillColor = rectItem.isSoildFill?rectItem.lineColor.CGColor:nil;
        if (rectItem.isSoildFill || rectItem.valueType == DrawingDownValue) {
            player.fillColor = rectItem.lineColor.CGColor;
        } else {
            player.fillColor = [UIColor clearColor].CGColor;
        }
        player.zPosition = 101;
        [player generateSubPath:^UIBezierPath *{
            return [self _generateCandlePathInRect:rectItem.pillarRect highPoint:rectItem.line1.start lowPoint:rectItem.line2.start isFill:rectItem.isSoildFill];
        }];
    }
    [self.player_up paintInLayer:layer];
    [self.player_down paintInLayer:layer];
    [self.player_equal paintInLayer:layer];
}
@end
